// 文件上传配置接口
export interface FileUploadConfig {
  accept?: string; // 接受的文件类型，如 "image" 或 "all"
  maxSize?: number; // 最大文件大小（MB）
  maxCount?: number; // 最大文件数量
  uploadUrl?: string; // 上传接口地址
  listType?: "text" | "picture" | "picture-card"; // 显示类型
  tips?: string; // 上传提示信息
}

// 选项数据接口
export interface OptionItem {
  value: string;
  text: string;
}

// 表单字段配置接口
export interface FieldConfig {
  key: string;
  label: string;
  type: "input" | "textarea" | "picker" | "datetime" | "date" | "native-date" | "image-upload" | "file-upload" | "readonly" | "department-picker" | "text" | "autocomplete";
  placeholder: string;
  required?: boolean;
  inputType?: string;
  maxlength?: number;
  pattern?: string; // 正则表达式验证
  patternErrorMessage?: string; // 正则验证失败的错误信息
  options?: string[];
  optionsData?: OptionItem[]; // 选项数据
  fileConfig?: FileUploadConfig; // 文件上传配置
  readonly?: boolean; // 只读字段标识
  showInCreate?: boolean; // 是否在新增页面显示
  showInEdit?: boolean; // 是否在编辑页面显示
  showInDetails?: boolean; // 是否在详情页面显示
  popupTitle?: string; // 弹窗标题（用于department-picker类型）
  departmentData?: any[]; // 部门数据（用于department-picker类型）
  // 自动补全相关配置
  searchApi?: (query: string) => Promise<OptionItem[]>; // 自动补全搜索API
  minSearchLength?: number; // 最小搜索长度
  debounceTime?: number; // 防抖时间
  // 原生日期选择器相关属性
  startDate?: string; // 开始日期
  endDate?: string; // 结束日期
  dateFormat?: 'YYYY-MM-DD' | 'YYYY/MM/DD' | 'MM/DD/YYYY'; // 日期格式
  disabled?: boolean; // 是否禁用
  validation?: (
    value: any,
    formData?: any,
  ) => { valid: boolean; message: string } | true;
}

// 表单分组接口
export interface FormSection {
  key: string;
  title: string;
  fields: FieldConfig[];
}

// 转正申请单表单配置
export const probationFormConfig: Record<string, FieldConfig> = {
  // 员工基本信息
  name: {
    key: "name",
    label: "姓名",
    type: "input",
    placeholder: "请输入员工姓名",
    required: true,
    maxlength: 50,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  staffNo: {
    key: "staffNo",
    label: "工号",
    type: "input",
    placeholder: "请输入员工工号",
    required: true,
    maxlength: 50,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  regularStaffNo: {
    key: "regularStaffNo",
    label: "转正后工号",
    type: "input",
    placeholder: "请输入转正后工号",
    required: false,
    maxlength: 50,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  gender: {
    key: "gender",
    label: "性别",
    type: "picker",
    placeholder: "请选择性别",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    options: ["男", "女", "未知"],
    optionsData: [
      { value: "1", text: "男" },
      { value: "2", text: "女" },
      { value: "0", text: "未知" }
    ],
  },
  phone: {
    key: "phone",
    label: "手机号",
    type: "input",
    placeholder: "请输入手机号",
    required: true,
    inputType: "tel",
    pattern: "^1[3-9]\\d{9}$",
    patternErrorMessage: "请输入正确的手机号格式",
    maxlength: 11,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  idCardNo: {
    key: "idCardNo",
    label: "身份证号",
    type: "input",
    placeholder: "请输入身份证号",
    required: true,
    pattern: "^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$",
    patternErrorMessage: "请输入正确的身份证号格式",
    maxlength: 18,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  birthDate: {
    key: "birthDate",
    label: "出生日期",
    type: "native-date",
    placeholder: "请选择出生日期",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    startDate: "1920-01-01",
    endDate: "2010-12-31",
    dateFormat: "YYYY-MM-DD",
  },
  orgId: {
    key: "orgId",
    label: "所属部门",
    type: "department-picker",
    placeholder: "请选择所属部门",
    popupTitle: "选择部门",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: false,
    departmentData: [], // 部门数据，将在页面加载时动态填充
  },
  org: {
    key: "org",
    label: "所属部门",
    type: "readonly",
    placeholder: "所属部门",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  companyId: {
    key: "companyId",
    label: "所属公司",
    type: "readonly",
    placeholder: "所属公司",
    required: false,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    optionsData: [], // 公司数据，将在页面加载时动态填充
  },
  email: {
    key: "email",
    label: "邮箱",
    type: "input",
    placeholder: "请输入邮箱地址",
    required: false,
    inputType: "email",
    pattern: "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",
    patternErrorMessage: "请输入正确的邮箱格式",
    maxlength: 100,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },

  // 转正基本信息
  entryDate: {
    key: "entryDate",
    label: "入职日期",
    type: "native-date",
    placeholder: "请选择入职日期",
    required: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    startDate: "2020-01-01",
    endDate: "2050-12-31",
    dateFormat: "YYYY-MM-DD",
  },
  regDate: {
    key: "regDate",
    label: "转正日期",
    type: "native-date",
    placeholder: "请选择转正日期",
    required: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    startDate: "2020-01-01",
    endDate: "2050-12-31",
    dateFormat: "YYYY-MM-DD",
  },

  // 试用期信息
  probationStartDate: {
    key: "probationStartDate",
    label: "试用期起始日期",
    type: "native-date",
    placeholder: "请选择试用期起始日期",
    required: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    startDate: "2020-01-01",
    endDate: "2050-12-31",
    dateFormat: "YYYY-MM-DD",
  },
  probationEndDate: {
    key: "probationEndDate",
    label: "试用期结束日期",
    type: "native-date",
    placeholder: "请选择试用期结束日期",
    required: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    startDate: "2020-01-01",
    endDate: "2050-12-31",
    dateFormat: "YYYY-MM-DD",
  },
  probationSalary: {
    key: "probationSalary",
    label: "试用期薪资",
    type: "input",
    placeholder: "请输入试用期薪资",
    required: false,
    inputType: "number",
    maxlength: 20,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },

  // 转正薪资信息
  regularSalary: {
    key: "regularSalary",
    label: "转正后薪资",
    type: "input",
    placeholder: "请输入转正后薪资",
    required: false,
    inputType: "number",
    maxlength: 20,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },

  // 转正评估内容
  jobContent: {
    key: "jobContent",
    label: "试用期工作内容",
    type: "textarea",
    placeholder: "请输入试用期工作内容",
    required: true,
    maxlength: 1000,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  jobAchievements: {
    key: "jobAchievements",
    label: "试用期工作成果",
    type: "textarea",
    placeholder: "请输入试用期工作成果",
    required: true,
    maxlength: 1000,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  regOpinion: {
    key: "regOpinion",
    label: "转正意见",
    type: "textarea",
    placeholder: "请输入转正意见",
    required: false,
    maxlength: 500,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  remarks: {
    key: "remarks",
    label: "其他说明",
    type: "textarea",
    placeholder: "请输入其他说明",
    required: false,
    maxlength: 500,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },

  // 单据信息
  billCode: {
    key: "billCode",
    label: "单据编号",
    type: "readonly",
    placeholder: "系统自动生成",
    required: false,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  billStatus: {
    key: "billStatus",
    label: "单据状态",
    type: "readonly",
    placeholder: "系统自动生成",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  remark: {
    key: "remark",
    label: "备注",
    type: "textarea",
    placeholder: "请输入备注信息",
    required: false,
    maxlength: 200,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },

  // 详情页面专用字段
  workflowStatus: {
    key: "workflowStatus",
    label: "工作流状态",
    type: "readonly",
    placeholder: "工作流状态",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  approver: {
    key: "approver",
    label: "审批人",
    type: "readonly",
    placeholder: "审批人",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  approvalTime: {
    key: "approvalTime",
    label: "审批时间",
    type: "readonly",
    placeholder: "审批时间",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
};

// 表单分组配置
export const formSections: FormSection[] = [
  {
    key: "employeeInfo",
    title: "员工基本信息",
    fields: [
      probationFormConfig.name,
      probationFormConfig.staffNo,
      probationFormConfig.regularStaffNo,
      probationFormConfig.gender,
      probationFormConfig.phone,
      probationFormConfig.idCardNo,
      probationFormConfig.birthDate,
      probationFormConfig.companyId,
      probationFormConfig.orgId,
      probationFormConfig.org,
      probationFormConfig.email,
    ],
  },
  {
    key: "probationBasicInfo",
    title: "转正基本信息",
    fields: [
      probationFormConfig.entryDate,
      probationFormConfig.regDate,
    ],
  },
  {
    key: "probationInfo",
    title: "试用期信息",
    fields: [
      probationFormConfig.probationStartDate,
      probationFormConfig.probationEndDate,
      probationFormConfig.probationSalary,
    ],
  },
  {
    key: "salaryInfo",
    title: "转正薪资信息",
    fields: [
      probationFormConfig.regularSalary,
    ],
  },
  {
    key: "evaluationInfo",
    title: "转正评估内容",
    fields: [
      probationFormConfig.jobContent,
      probationFormConfig.jobAchievements,
      probationFormConfig.regOpinion,
      probationFormConfig.remarks,
    ],
  },
  {
    key: "billInfo",
    title: "单据信息",
    fields: [
      probationFormConfig.billCode,
      probationFormConfig.billStatus,
      probationFormConfig.workflowStatus,
      probationFormConfig.remark,
    ],
  },
  {
    key: "workflowInfo",
    title: "流程信息",
    fields: [
      probationFormConfig.approver,
      probationFormConfig.approvalTime,
    ],
  },
];

// 根据页面类型过滤表单分组
export const getFormSectionsByPageType = (pageType: 'create' | 'edit' | 'details'): FormSection[] => {
  return formSections.map(section => ({
    ...section,
    fields: section.fields.filter(field => {
      if (pageType === 'create') {
        return field.showInCreate !== false;
      } else if (pageType === 'edit') {
        return field.showInEdit !== false;
      } else if (pageType === 'details') {
        // 详情页根据showInDetails配置显示字段
        return field.showInDetails !== false;
      }
      return false;
    })
  })).filter(section => section.fields.length > 0);
};

// 表单验证函数
export const validateForm = (
  formData: Record<string, any>,
): { valid: boolean; errors: Record<string, string> } => {
  const errors: Record<string, string> = {};
  let valid = true;

  // 遍历所有字段配置
  Object.values(probationFormConfig).forEach((field) => {
    const value = formData[field.key];

    // 必填字段验证
    if (field.required && !value) {
      errors[field.key] = `请输入${field.label}`;
      valid = false;
      return;
    }

    // 正则表达式验证
    if (field.pattern && value) {
      const pattern = new RegExp(field.pattern);
      if (!pattern.test(value)) {
        errors[field.key] =
          field.patternErrorMessage || `${field.label}格式不正确`;
        valid = false;
        return;
      }
    }

    // 自定义验证
    if (field.validation && value !== undefined) {
      const result = field.validation(value, formData);
      if (result !== true) {
        errors[field.key] = result.message;
        valid = false;
        return;
      }
    }
  });

  return { valid, errors };
};
